﻿using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace NetTrafficStatistics
{
	static class Program
	{
		[STAThread]
		private static void Main (string[] args)
		{
			try
			{
				Tools.LogFile = Application.ExecutablePath + ".log";
				Tools.TmpFile = Application.ExecutablePath + ".tmp";
				//System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
				var p = Process.GetCurrentProcess ();
				var file = Path.GetFileNameWithoutExtension (Application.ExecutablePath);

				// Used to start/stop application during install/uninstall
				if (args.Length == 1)
				{
					switch (args[0])
					{
						case "start":

							ProcessStartInfo psi = new ProcessStartInfo
							{
								FileName = Application.ExecutablePath,
								UseShellExecute = false,
								WorkingDirectory = Path.GetDirectoryName (Application.ExecutablePath)
							};
							Process.Start (psi);
							return;

						case "stop":

							foreach (var clsProcess in Process.GetProcesses ())
							{
								if ((p.Id != clsProcess.Id) && clsProcess.ProcessName.StartsWith (file))
								{
									clsProcess.Kill();
								}
							}
							return;
					}
				}

				// Find duplicate process
				foreach (var clsProcess in Process.GetProcesses ())
				{
					if ((p.Id != clsProcess.Id) && clsProcess.ProcessName.StartsWith (file))
					{
						return;
					}
				}

				// Main section
				SqLiteDb.Start();
				Sniffer.Start();

				// Starting Main Form
				Application.EnableVisualStyles();
				Application.SetCompatibleTextRenderingDefault (false);
				Application.Run (new MainForm());

				Sniffer.Stop();
				SqLiteDb.Close();
			}
			catch (Exception e)
			{
				Tools.WriteLogs (e.ToString());
			}
		}
	}
}
